package org.jim.server.command.cs;

import org.apache.commons.lang3.StringUtils;
import org.jim.connector.command.CsAllocHelper;
import org.jim.core.ImChannelContext;
import org.jim.core.ImConst;
import org.jim.core.ImPacket;
import org.jim.core.ImStatus;
import org.jim.core.config.ImConfig;
import org.jim.core.exception.ImException;
import org.jim.core.helper.MessageHelper;
import org.jim.core.packets.pub.consts.Command;
import org.jim.core.packets.RespBody;
import org.jim.core.packets.cs.chat.command.CsMessageReqCmd;
import org.jim.core.packets.cs.session.vo.JimCsMessageResp;
import org.jim.core.packets.cs.user.vo.UserMessageData;
import org.jim.core.utils.JsonKit;
import org.jim.server.command.AbstractCmdHandler;
import org.jim.server.command.CommandHandler;
import org.jim.server.config.ImServerConfig;
import org.jim.server.protocol.ProtocolManager;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 获取聊天消息命令处理器
 *
 * @author WChao
 * @date 2018年4月10日 下午2:40:07
 */
@CommandHandler(cmd = Command.COMMAND_GET_MESSAGE_REQ)
public class CsMessageReqHandler extends AbstractCmdHandler {
    @Autowired
    private CsAllocHelper csAllocHelper;
    @Override
    public Command command() {

        return Command.COMMAND_GET_MESSAGE_REQ;
    }

    @Override
    public ImPacket handler(ImPacket packet, ImChannelContext imChannelContext) throws ImException {
        RespBody resPacket;
        CsMessageReqCmd messageReqBody;
        try {
            messageReqBody = JsonKit.toBean(packet.getBody(), CsMessageReqCmd.class);
        } catch (Exception e) {
            //用户消息格式不正确
            return getMessageFailedPacket(imChannelContext);
        }
        //测试离线消息
        csAllocHelper.offlineAlloc();
        UserMessageData messageData = null;
        ImServerConfig imServerConfig = ImConfig.Global.get();
        MessageHelper messageHelper = imServerConfig.getMessageHelper();
        //群组ID;
        String groupId = messageReqBody.getGroupId();
        //当前用户ID;
        String userId = messageReqBody.getUserId();
        //消息来源用户ID;
        String fromUserId = messageReqBody.getFromUserId();
        //消息区间开始时间;
        Double beginTime = messageReqBody.getBeginTime();
        //消息区间结束时间;
        Double endTime = messageReqBody.getEndTime();
        //分页偏移量;
        Integer offset = messageReqBody.getOffset();
        //分页数量;
        Integer count = messageReqBody.getCount();
        //消息类型;
        int type = messageReqBody.getType();
        //如果用户ID为空或者type格式不正确，获取消息失败;
        if (StringUtils.isEmpty(userId) || (0 != type && 1 != type) || !ImServerConfig.ON.equals(imServerConfig.getIsStore())) {
            return getMessageFailedPacket(imChannelContext);
        }
        if (type == 0) {
            resPacket = new RespBody(Command.COMMAND_GET_MESSAGE_RESP, ImStatus.C10016);
        } else {
            resPacket = new RespBody(Command.COMMAND_GET_MESSAGE_RESP, ImStatus.C10018);
        }
        //带操作类型
        if (ImConst.USER_OPERATE.equals(messageReqBody.getOperateType())) {
            //客户查询记录
            if (0 == type) {
                //查询 离线
                if(StringUtils.isBlank(fromUserId)){
                    //查询与所有租户的离线消息
                    resPacket.setData( messageHelper.getCsChatHelper().getCsOfflineMessage(userId));
                }else{
                    //查询与某租户的离线消息
                    resPacket.setData( messageHelper.getCsChatHelper().getCsOfflineMessage(userId,fromUserId));
                }
            } else if (1 == type) {
                //查询历史
                List<JimCsMessageResp> list = messageHelper.getCsChatHelper().getHistoryMessage(userId, fromUserId, beginTime, endTime, offset, count);
                resPacket.setData(list);
            }
        } else if (ImConst.CS_OPERATE.equals(messageReqBody.getOperateType())) {
            //客服查询记录
            //客服直接查询数据库
            if (0 == type) {
                //查询 离线
            } else if (1 == type) {
                //查询历史
                List<JimCsMessageResp> list = messageHelper.getCsChatHelper().getCsHistoryMessage(userId, fromUserId, beginTime, endTime, offset, count);
                resPacket.setData(list);
            }
        }

        return ProtocolManager.Converter.respPacket(resPacket, imChannelContext);
    }

    /**
     * 获取用户消息失败响应包;
     *
     * @param imChannelContext
     * @return
     */
    public ImPacket getMessageFailedPacket(ImChannelContext imChannelContext) throws ImException {
        RespBody resPacket = new RespBody(Command.COMMAND_GET_MESSAGE_RESP, ImStatus.C10015);
        return ProtocolManager.Converter.respPacket(resPacket, imChannelContext);
    }
}
